package com.learning.springmvc.advance.valid.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * ClassName: WebMvcConfig
 * Description: Spring MVC 配置 继承自{@link WebMvcConfigurerAdapter}。可以理解为 WebApplicationContext 容器的配置
 * <p>
 * Date: 2019/5/13 15:46 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.learning.springmvc.advance", useDefaultFilters = false,
        includeFilters = {@ComponentScan.Filter(classes = Controller.class)})
public class WebMvcConfig extends WebMvcConfigurerAdapter {


    /**
     * 默认是系统也是这个 OptionalValidatorFactoryBean
     * 自定义注解实现时，资源国际需要这边自定义加入
     *
     * @return
     */
    @Override
    public Validator getValidator() {
        OptionalValidatorFactoryBean validatorFactoryBean = new OptionalValidatorFactoryBean();
        validatorFactoryBean.setValidationMessageSource(messageSource());
        return validatorFactoryBean;
    }


    /**
     * 资源国际化
     *
     * @return
     */
    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setBasenames("messages/messages");
        return messageSource;
    }
}
